package com.fjnu.service.impl;

import com.fjnu.annotation.ExceptionGlobalCatch;
import com.fjnu.dao.CategoryDao;
import com.fjnu.domain.entity.Category;
import com.fjnu.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@ExceptionGlobalCatch
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    @Transactional
    public int deleteCategory(Integer categoryId) {
        if (categoryId == null || categoryId <= 0) {
            throw new IllegalArgumentException("分类ID不能为空和小于等于0");
        }

        // 检查分类是否存在
        Category category = categoryDao.selectById(categoryId);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }

        int result = categoryDao.delete(categoryId);
        if (result == 0) {
            throw new RuntimeException("删除分类失败");
        }
        return result;
    }

    @Override
    public int addCategory(Category category) {
        if (category == null) {
            throw new IllegalArgumentException("分类信息不能为空");
        }

        if (category.getName() == null || category.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("分类名称不能为空");
        }

        // 检查分类名称是否已存在
        Category existingCategory = categoryDao.selectByName(category.getName().trim());
        if (existingCategory != null) {
            throw new RuntimeException("分类名称已存在");
        }

        int result = categoryDao.insert(category);
        if (result == 0) {
            throw new RuntimeException("添加分类失败");
        }
        return result;
    }

    @Override
    public List<Category> getAllCategories() {
        List<Category> categories = categoryDao.selectAll();
        return categories != null ? categories : java.util.Collections.emptyList();
    }
}